<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>权限管理系统 - 管理后台</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        :root {
            --primary: #667eea;
            --secondary: #764ba2;
            --success: #10b981;
            --info: #3b82f6;
            --warning: #f59e0b;
            --danger: #ef4444;
        }

        body {
            background: linear-gradient(135deg, var(--primary) 0%, var(--secondary) 100%);
            min-height: 100vh;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        .main-container {
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.1);
            margin: 30px auto;
            min-height: 80vh;
            overflow: hidden;
        }

        .sidebar {
            background: linear-gradient(180deg, #2d3748 0%, #4a5568 100%);
            color: white;
            height: 100%;
            padding: 0;
        }

        .sidebar-header {
            padding: 30px 20px;
            text-align: center;
            border-bottom: 1px solid #4a5568;
        }

        .nav-link {
            color: #cbd5e0;
            padding: 15px 20px;
            border-left: 4px solid transparent;
            transition: all 0.3s ease;
        }

        .nav-link:hover, .nav-link.active {
            color: white;
            background: rgba(255,255,255,0.1);
            border-left-color: var(--primary);
        }

        .nav-link i {
            width: 20px;
            margin-right: 10px;
        }

        .content-header {
            background: #f8fafc;
            border-bottom: 1px solid #e2e8f0;
            padding: 25px 30px;
        }

        .content-body {
            padding: 30px;
            background: #f8fafc;
            min-height: 500px;
        }

        .search-box {
            background: white;
            border-radius: 15px;
            padding: 25px;
            margin-bottom: 25px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
            border: 1px solid #e2e8f0;
        }

        .result-card {
            background: white;
            border-radius: 15px;
            padding: 25px;
            margin-bottom: 20px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
            border: 1px solid #e2e8f0;
            transition: all 0.3s ease;
        }

        .result-card:hover {
            box-shadow: 0 10px 25px rgba(0,0,0,0.15);
            transform: translateY(-2px);
        }

        .role-badge {
            background: #e8f5e8;
            color: #2e7d32;
            padding: 6px 12px;
            border-radius: 15px;
            font-size: 0.8rem;
            margin: 3px;
            display: inline-block;
            border: 1px solid #c8e6c9;
        }

        .menu-badge {
            background: #e3f2fd;
            color: #1565c0;
            padding: 6px 12px;
            border-radius: 15px;
            font-size: 0.8rem;
            margin: 3px;
            display: inline-block;
            border: 1px solid #bbdefb;
        }

        .user-avatar {
            width: 60px;
            height: 60px;
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 1.2rem;
            margin-right: 15px;
        }

        .pagination-container {
            background: white;
            border-radius: 12px;
            padding: 20px;
            margin-top: 20px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
        }

        .stats-card {
            background: white;
            border-radius: 15px;
            padding: 25px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
            border-left: 4px solid var(--primary);
            transition: transform 0.3s ease;
            text-align: center;
        }

        .stats-card:hover {
            transform: translateY(-5px);
        }

        .stats-icon {
            width: 70px;
            height: 70px;
            border-radius: 15px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.8rem;
            margin: 0 auto 15px;
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            color: white;
        }

        .permission-item {
            background: #f8fafc;
            border: 1px solid #e2e8f0;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 10px;
            transition: all 0.3s ease;
        }

        .permission-item:hover {
            background: #f1f5f9;
            border-color: var(--primary);
        }

        .form-check-input:checked {
            background-color: var(--success);
            border-color: var(--success);
        }

        .action-buttons .btn {
            margin: 2px;
        }
    </style>
</head>
<body>
<div class="container-fluid">
    <div class="row main-container">
        <!-- 侧边栏 -->
        <div class="col-md-3 col-lg-2 sidebar">
            <div class="sidebar-header">
                <h4><i class="fas fa-shield-alt"></i> 权限管理系统</h4>
                <small class="text-muted">MyBatis高级应用作业</small>
            </div>
            <nav class="nav flex-column">
                <a class="nav-link active" href="#" onclick="showSection('dashboard')">
                    <i class="fas fa-tachometer-alt"></i> 系统概览
                </a>
                <a class="nav-link" href="#" onclick="showSection('task1')">
                    <i class="fas fa-user"></i> 用户角色查询
                </a>
                <a class="nav-link" href="#" onclick="showSection('task2')">
                    <i class="fas fa-shield-alt"></i> 角色权限查询
                </a>
                <a class="nav-link" href="#" onclick="showSection('task3')">
                    <i class="fas fa-search"></i> 综合用户查询
                </a>
                <a class="nav-link" href="#" onclick="showSection('task4')">
                    <i class="fas fa-cogs"></i> 权限维护
                </a>
            </nav>
        </div>

        <!-- 主内容区 -->
        <div class="col-md-9 col-lg-10">
            <!-- 内容头部 -->
            <div class="content-header">
                <h3 id="sectionTitle">系统概览</h3>
                <p id="sectionDescription" class="text-muted mb-0">权限管理系统数据概览</p>
            </div>

            <!-- 内容主体 -->
            <div class="content-body">
                <!-- 系统概览 -->
                <div id="dashboard" class="section-content">
                    <div class="row mb-4">
                        <div class="col-md-3">
                            <div class="stats-card">
                                <div class="stats-icon">
                                    <i class="fas fa-users"></i>
                                </div>
                                <h3 id="userCount">6</h3>
                                <p class="text-muted mb-0">总用户数</p>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="stats-card">
                                <div class="stats-icon">
                                    <i class="fas fa-user-shield"></i>
                                </div>
                                <h3 id="roleCount">3</h3>
                                <p class="text-muted mb-0">角色数量</p>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="stats-card">
                                <div class="stats-icon">
                                    <i class="fas fa-list"></i>
                                </div>
                                <h3 id="menuCount">9</h3>
                                <p class="text-muted mb-0">菜单权限</p>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="stats-card">
                                <div class="stats-icon">
                                    <i class="fas fa-link"></i>
                                </div>
                                <h3 id="relationCount">9</h3>
                                <p class="text-muted mb-0">权限关系</p>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-8">
                            <div class="search-box">
                                <h5><i class="fas fa-chart-bar me-2"></i>数据统计</h5>
                                <div class="row text-center">
                                    <div class="col-4">
                                        <div class="border rounded p-3">
                                            <h4 class="text-primary" id="activeUsers">6</h4>
                                            <small class="text-muted">活跃用户</small>
                                        </div>
                                    </div>
                                    <div class="col-4">
                                        <div class="border rounded p-3">
                                            <h4 class="text-success" id="userWithRoles">1</h4>
                                            <small class="text-muted">有角色用户</small>
                                        </div>
                                    </div>
                                    <div class="col-4">
                                        <div class="border rounded p-3">
                                            <h4 class="text-info" id="avgRoles">0.17</h4>
                                            <small class="text-muted">平均角色数</small>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="search-box">
                                <h5><i class="fas fa-info-circle me-2"></i>系统信息</h5>
                                <div class="row">
                                    <div class="col-12 mb-2">
                                        <small class="text-muted">数据库连接</small>
                                        <div id="dbStatus" class="badge bg-success">正常</div>
                                    </div>
                                    <div class="col-12 mb-2">
                                        <small class="text-muted">API状态</small>
                                        <div id="apiStatus" class="badge bg-success">正常</div>
                                    </div>
                                    <div class="col-12">
                                        <small class="text-muted">最后更新</small>
                                        <div id="lastUpdate" class="text-muted">刚刚</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 任务一：用户角色查询 -->
                <div id="task1" class="section-content" style="display: none;">
                    <div class="search-box">
                        <h5><i class="fas fa-user me-2"></i>用户角色查询 - 一对多查询</h5>
                        <div class="row g-3 align-items-end">
                            <div class="col-md-6">
                                <label class="form-label">用户名</label>
                                <input type="text" class="form-control" id="usernameSearch" placeholder="输入用户名，支持模糊匹配" value="admin">
                                <div class="form-text">支持模糊匹配，如输入"adm"可匹配"admin"</div>
                            </div>
                            <div class="col-md-6">
                                <button class="btn btn-primary w-100" onclick="searchUserWithRoles()">
                                    <i class="fas fa-search me-2"></i>查询用户角色
                                </button>
                            </div>
                        </div>
                    </div>

                    <div id="userRolesResult">
                        <div class="text-center py-5">
                            <i class="fas fa-user fa-3x text-muted mb-3"></i>
                            <p class="text-muted">请输入用户名查询用户角色信息</p>
                            <small class="text-muted">展示一对多查询结果：用户 → 多个角色</small>
                        </div>
                    </div>
                </div>

                <!-- 任务二：角色权限查询 -->
                <div id="task2" class="section-content" style="display: none;">
                    <div class="search-box">
                        <h5><i class="fas fa-shield-alt me-2"></i>角色权限查询 - 多层一对多查询</h5>
                        <div class="row g-3 align-items-end">
                            <div class="col-md-4">
                                <label class="form-label">角色ID</label>
                                <input type="number" class="form-control" id="roleIdSearch" placeholder="输入角色ID" value="1">
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">角色名称</label>
                                <input type="text" class="form-control" id="roleNameSearch" placeholder="输入角色名称模糊匹配">
                            </div>
                            <div class="col-md-4">
                                <button class="btn btn-primary w-100" onclick="searchRoleWithMenus()">
                                    <i class="fas fa-search me-2"></i>查询角色权限
                                </button>
                            </div>
                        </div>
                    </div>

                    <div id="roleMenusResult">
                        <div class="text-center py-5">
                            <i class="fas fa-shield-alt fa-3x text-muted mb-3"></i>
                            <p class="text-muted">请输入角色ID或名称查询角色权限信息</p>
                            <small class="text-muted">展示多层一对多查询结果：角色 → 多个菜单权限</small>
                        </div>
                    </div>
                </div>

                <!-- 任务三：综合用户查询 -->
                <div id="task3" class="section-content" style="display: none;">
                    <div class="search-box">
                        <h5><i class="fas fa-search me-2"></i>综合用户查询 - 动态SQL + 多表关联</h5>
                        <div class="row g-3">
                            <div class="col-md-3">
                                <label class="form-label">用户名</label>
                                <input type="text" class="form-control" id="searchUsername" placeholder="用户名模糊匹配">
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">邮箱</label>
                                <input type="text" class="form-control" id="searchEmail" placeholder="邮箱模糊匹配">
                            </div>
                            <div class="col-md-2">
                                <label class="form-label">状态</label>
                                <select class="form-select" id="searchStatus">
                                    <option value="">全部状态</option>
                                    <option value="0">正常</option>
                                    <option value="1">禁用</option>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label class="form-label">每页数量</label>
                                <select class="form-select" id="pageSizeSelect">
                                    <option value="5">5条</option>
                                    <option value="10" selected>10条</option>
                                    <option value="20">20条</option>
                                    <option value="50">50条</option>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label class="form-label">&nbsp;</label>
                                <button class="btn btn-primary w-100" onclick="searchUsers()">
                                    <i class="fas fa-search me-2"></i>查询
                                </button>
                            </div>
                        </div>
                        <div class="row mt-3">
                            <div class="col-12">
                                <button class="btn btn-outline-secondary" onclick="resetSearch()">
                                    <i class="fas fa-redo me-2"></i>重置条件
                                </button>
                                <small class="text-muted ms-3">使用动态SQL构建查询条件，支持多表关联查询</small>
                            </div>
                        </div>
                    </div>

                    <div id="usersSearchResult">
                        <div class="text-center py-5">
                            <i class="fas fa-users fa-3x text-muted mb-3"></i>
                            <p class="text-muted">设置查询条件搜索用户信息</p>
                            <small class="text-muted">展示多对多查询结果：用户 ↔ 角色 ↔ 菜单权限</small>
                        </div>
                    </div>

                    <div class="pagination-container" id="paginationContainer" style="display: none;">
                        <div class="row align-items-center">
                            <div class="col-md-6">
                                <small class="text-muted" id="pageInfo">第 1 页，共 1 页</small>
                            </div>
                            <div class="col-md-6">
                                <nav>
                                    <ul class="pagination justify-content-end mb-0" id="pagination">
                                    </ul>
                                </nav>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 任务四：权限维护 -->
                <div id="task4" class="section-content" style="display: none;">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="search-box">
                                <h5><i class="fas fa-user-cog me-2"></i>用户角色维护</h5>
                                <div class="mb-3">
                                    <label class="form-label">选择用户</label>
                                    <select class="form-select" id="userSelect" onchange="loadUserRoles()">
                                        <option value="">请选择用户</option>
                                    </select>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">分配角色</label>
                                    <div id="roleCheckboxes">
                                        <!-- 角色复选框动态加载 -->
                                    </div>
                                </div>
                                <button class="btn btn-success w-100" onclick="updateUserRoles()">
                                    <i class="fas fa-save me-2"></i>保存用户角色设置
                                </button>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="search-box">
                                <h5><i class="fas fa-shield-alt me-2"></i>角色权限维护</h5>
                                <div class="mb-3">
                                    <label class="form-label">选择角色</label>
                                    <select class="form-select" id="roleSelect" onchange="loadRoleMenus()">
                                        <option value="">请选择角色</option>
                                    </select>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">分配菜单权限</label>
                                    <div id="menuCheckboxes" style="max-height: 300px; overflow-y: auto;">
                                        <!-- 菜单复选框动态加载 -->
                                    </div>
                                </div>
                                <button class="btn btn-success w-100" onclick="updateRoleMenus()">
                                    <i class="fas fa-save me-2"></i>保存角色权限设置
                                </button>
                            </div>
                        </div>
                    </div>

                    <div class="search-box mt-4">
                        <h5><i class="fas fa-history me-2"></i>操作日志</h5>
                        <div id="operationLog" class="text-muted">
                            <p class="mb-2">暂无操作记录</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
    // 配置
    const CONFIG = {
        baseUrl: 'http://localhost:8080/mybatis-homework',
        currentPage: 1,
        pageSize: 10
    };

    // 显示对应区域
    function showSection(sectionId) {
        // 隐藏所有区域
        document.querySelectorAll('.section-content').forEach(section => {
            section.style.display = 'none';
        });

        // 移除所有active类
        document.querySelectorAll('.nav-link').forEach(link => {
            link.classList.remove('active');
        });

        // 显示目标区域
        document.getElementById(sectionId).style.display = 'block';

        // 设置active类
        event.target.classList.add('active');

        // 更新标题
        updateSectionTitle(sectionId);

        // 加载对应数据
        loadSectionData(sectionId);
    }

    function updateSectionTitle(sectionId) {
        const titles = {
            'dashboard': '系统概览',
            'task1': '用户角色查询 - 一对多查询',
            'task2': '角色权限查询 - 多层一对多查询',
            'task3': '综合用户查询 - 动态SQL + 多表关联',
            'task4': '权限维护 - 用户角色和角色权限设置'
        };

        const descriptions = {
            'dashboard': '权限管理系统数据概览和统计信息',
            'task1': '查询特定用户及其拥有的所有角色（一对多查询）',
            'task2': '查询特定角色及其所拥有的所有菜单权限（多层一对多查询）',
            'task3': '根据条件搜索用户，并连带其角色和权限信息（多对多查询 + 动态SQL）',
            'task4': '用户角色分配和角色权限设置'
        };

        document.getElementById('sectionTitle').textContent = titles[sectionId];
        document.getElementById('sectionDescription').textContent = descriptions[sectionId];
    }

    function loadSectionData(sectionId) {
        switch(sectionId) {
            case 'dashboard':
                loadDashboardData();
                break;
            case 'task1':
                // 默认加载admin用户
                searchUserWithRoles();
                break;
            case 'task2':
                // 默认加载角色1
                searchRoleWithMenus();
                break;
            case 'task3':
                // 加载第一页用户
                loadUsersPage(1);
                break;
            case 'task4':
                // 加载权限维护数据
                loadPermissionData();
                break;
        }
    }

    // 任务一：查询用户角色
    async function searchUserWithRoles() {
        const username = document.getElementById('usernameSearch').value;
        if (!username) {
            alert('请输入用户名');
            return;
        }

        try {
            const response = await fetch(`${CONFIG.baseUrl}/api/users/username/${username}`);
            const result = await response.json();

            if (result.success && result.data) {
                displayUserWithRoles(result.data);
            } else {
                document.getElementById('userRolesResult').innerHTML = `
                    <div class="alert alert-danger text-center">
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        用户不存在或查询失败: ${result.message}
                    </div>
                `;
            }
        } catch (error) {
            console.error('查询用户角色失败:', error);
            document.getElementById('userRolesResult').innerHTML = `
                <div class="alert alert-danger text-center">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    查询过程中发生错误
                </div>
            `;
        }
    }

    function displayUserWithRoles(user) {
        const rolesHtml = user.roles && user.roles.length > 0
            ? user.roles.map(role => {
                const descriptionHtml = role.description
                    ? `<small class="ms-1">(${role.description})</small>`
                    : '';

                return `<span class="role-badge">
                    <i class="fas fa-shield-alt me-1"></i>${role.name}
                    ${descriptionHtml}
                </span>`;
            }).join('')
            : '<span class="text-muted">该用户暂无角色</span>';

        document.getElementById('userRolesResult').innerHTML = `
            <div class="result-card">
                <div class="row">
                    <div class="col-md-3 text-center">
                        <div class="user-avatar mx-auto mb-3">
                            <i class="fas fa-user"></i>
                        </div>
                        <h5>${user.name}</h5>
                        <span class="badge ${user.status == 0 ? 'bg-success' : 'bg-danger'}">
                            ${user.status == 0 ? '正常' : '禁用'}
                        </span>
                    </div>
                    <div class="col-md-9">
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <strong><i class="fas fa-id-card me-2"></i>登录名:</strong> ${user.loginname}
                            </div>
                            <div class="col-md-6">
                                <strong><i class="fas fa-envelope me-2"></i>邮箱:</strong> ${user.email || '未设置'}
                            </div>
                        </div>
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <strong><i class="fas fa-phone me-2"></i>手机:</strong> ${user.mobilephone || '未设置'}
                            </div>
                            <div class="col-md-6">
                                <strong><i class="fas fa-venus-mars me-2"></i>性别:</strong> ${getGenderText(user.sex)}
                            </div>
                        </div>
                        <div class="mb-3">
                            <strong><i class="fas fa-user-shield me-2"></i>拥有角色 (${user.roles ? user.roles.length : 0}个):</strong>
                            <div class="mt-2">${rolesHtml}</div>
                        </div>
                        <div class="text-end">
                            <small class="text-muted">用户ID: ${user.id} | 创建时间: ${formatDate(user.createTime)}</small>
                        </div>
                    </div>
                </div>
            </div>
        `;
    }

    // 任务二：查询角色权限
    async function searchRoleWithMenus() {
        const roleId = document.getElementById('roleIdSearch').value;
        const roleName = document.getElementById('roleNameSearch').value;

        if (!roleId && !roleName) {
            alert('请输入角色ID或角色名称');
            return;
        }

        try {
            // 优先使用角色ID查询
            const response = await fetch(`${CONFIG.baseUrl}/api/roles/${roleId || '1'}`);
            const result = await response.json();

            if (result.success && result.data) {
                displayRoleWithMenus(result.data);
            } else {
                document.getElementById('roleMenusResult').innerHTML = `
                    <div class="alert alert-danger text-center">
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        角色不存在或查询失败: ${result.message}
                    </div>
                `;
            }
        } catch (error) {
            console.error('查询角色权限失败:', error);
            document.getElementById('roleMenusResult').innerHTML = `
                <div class="alert alert-danger text-center">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    查询过程中发生错误
                </div>
            `;
        }
    }

    function displayRoleWithMenus(role) {
        const menusHtml = role.menus && role.menus.length > 0
            ? role.menus.map(menu => {
                const urlHtml = menu.url
                    ? `<small class="ms-1">(${menu.url})</small>`
                    : '';

                return `<span class="menu-badge">
                    <i class="fas ${getMenuIcon(menu.type)} me-1"></i>${menu.name}
                    ${urlHtml}
                </span>`;
            }).join('')
            : '<span class="text-muted">该角色暂无菜单权限</span>';

        document.getElementById('roleMenusResult').innerHTML = `
            <div class="result-card">
                <div class="row">
                    <div class="col-md-3 text-center">
                        <div class="user-avatar mx-auto mb-3" style="background: linear-gradient(135deg, #f59e0b, #d97706);">
                            <i class="fas fa-shield-alt"></i>
                        </div>
                        <h5>${role.name}</h5>
                        <span class="badge ${role.status == 0 ? 'bg-success' : 'bg-danger'}">
                            ${role.status == 0 ? '正常' : '禁用'}
                        </span>
                    </div>
                    <div class="col-md-9">
                        <div class="row mb-3">
                            <div class="col-md-12">
                                <strong><i class="fas fa-info-circle me-2"></i>角色描述:</strong>
                                ${role.description || '暂无描述'}
                            </div>
                        </div>
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <strong><i class="fas fa-list me-2"></i>菜单数量:</strong> ${role.menus ? role.menus.length : 0}
                            </div>
                            <div class="col-md-6">
                                <strong><i class="fas fa-calendar me-2"></i>创建时间:</strong> ${formatDate(role.createTime)}
                            </div>
                        </div>
                        <div class="mb-3">
                            <strong><i class="fas fa-list-alt me-2"></i>菜单权限 (${role.menus ? role.menus.length : 0}个):</strong>
                            <div class="mt-2">${menusHtml}</div>
                        </div>
                        <div class="text-end">
                            <small class="text-muted">角色ID: ${role.id} | 版本: ${role.version || 0}</small>
                        </div>
                    </div>
                </div>
            </div>
        `;
    }

    // 任务三：综合用户查询
    async function searchUsers() {
        loadUsersPage(1);
    }

    async function loadUsersPage(page) {
        const username = document.getElementById('searchUsername').value;
        const email = document.getElementById('searchEmail').value;
        const status = document.getElementById('searchStatus').value;
        const pageSize = document.getElementById('pageSizeSelect').value;

        try {
            const params = new URLSearchParams({
                username: username || '',
                email: email || '',
                status: status || '',
                page: page,
                pageSize: pageSize
            });

            const response = await fetch(`${CONFIG.baseUrl}/api/users/search?${params}`);
            const result = await response.json();

            if (result.success) {
                displayUsersSearchResult(result.data, result);
                setupPagination(result, page);
            } else {
                document.getElementById('usersSearchResult').innerHTML = `
                    <div class="alert alert-danger text-center">
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        查询失败: ${result.message}
                    </div>
                `;
            }
        } catch (error) {
            console.error('查询用户失败:', error);
            document.getElementById('usersSearchResult').innerHTML = `
                <div class="alert alert-danger text-center">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    查询过程中发生错误
                </div>
            `;
        }
    }

    function displayUsersSearchResult(users, result) {
        if (!users || users.length === 0) {
            document.getElementById('usersSearchResult').innerHTML = `
                <div class="alert alert-info text-center">
                    <i class="fas fa-info-circle me-2"></i>
                    没有找到符合条件的用户
                </div>
            `;
            document.getElementById('paginationContainer').style.display = 'none';
            return;
        }

        const usersHtml = users.map(user => {
            const rolesHtml = user.roles && user.roles.length > 0
                ? user.roles.map(role => {
                    const descriptionHtml = role.description
                        ? `<small class="ms-1">(${role.description})</small>`
                        : '';

                    return `<span class="role-badge">
                        <i class="fas fa-shield-alt me-1"></i>${role.name}
                        ${descriptionHtml}
                    </span>`;
                }).join('')
                : '<span class="text-muted">无角色</span>';

            return `
                <div class="result-card">
                    <div class="row align-items-center">
                        <div class="col-md-1 text-center">
                            <div class="user-avatar">
                                <i class="fas fa-user"></i>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <h6 class="mb-1">${user.name}</h6>
                            <small class="text-muted">${user.loginname}</small>
                        </div>
                        <div class="col-md-3">
                            <small class="text-muted">${user.email || '无邮箱'}</small>
                            <br>
                            <small class="text-muted">${user.mobilephone || '无手机'}</small>
                        </div>
                        <div class="col-md-2">
                            <span class="badge ${user.status == 0 ? 'bg-success' : 'bg-danger'}">
                                ${user.status == 0 ? '正常' : '禁用'}
                            </span>
                        </div>
                        <div class="col-md-3">
                            <div class="text-truncate">${rolesHtml}</div>
                        </div>
                    </div>
                </div>
            `;
        }).join('');

        document.getElementById('usersSearchResult').innerHTML = usersHtml;
        document.getElementById('paginationContainer').style.display = 'block';
    }

    function setupPagination(result, currentPage) {
        const totalPages = result.totalPages || 1;
        const pageInfo = `第 ${currentPage} 页，共 ${totalPages} 页，总计 ${result.total} 条记录`;
        document.getElementById('pageInfo').textContent = pageInfo;

        let paginationHtml = '';

        // 上一页
        if (currentPage > 1) {
            paginationHtml += `
                <li class="page-item">
                    <a class="page-link" href="#" onclick="loadUsersPage(${currentPage - 1})">上一页</a>
                </li>
            `;
        }

        // 页码
        for (let i = 1; i <= totalPages; i++) {
            if (i === currentPage) {
                paginationHtml += `
                    <li class="page-item active">
                        <a class="page-link" href="#">${i}</a>
                    </li>
                `;
            } else {
                paginationHtml += `
                    <li class="page-item">
                        <a class="page-link" href="#" onclick="loadUsersPage(${i})">${i}</a>
                    </li>
                `;
            }
        }

        // 下一页
        if (currentPage < totalPages) {
            paginationHtml += `
                <li class="page-item">
                    <a class="page-link" href="#" onclick="loadUsersPage(${currentPage + 1})">下一页</a>
                </li>
            `;
        }

        document.getElementById('pagination').innerHTML = paginationHtml;
    }

    function resetSearch() {
        document.getElementById('searchUsername').value = '';
        document.getElementById('searchEmail').value = '';
        document.getElementById('searchStatus').value = '';
        document.getElementById('pageSizeSelect').value = '10';
    }

    // 任务四：权限维护
    // 任务四：权限维护
    async function loadPermissionData() {
        // 加载用户列表
        try {
            const response = await fetch(`${CONFIG.baseUrl}/api/users/search?page=1&pageSize=100`);
            const result = await response.json();

            if (result.success) {
                const userSelect = document.getElementById('userSelect');
                userSelect.innerHTML = '<option value="">请选择用户</option>';
                result.data.forEach(user => {
                    const option = document.createElement('option');
                    option.value = user.id;
                    option.textContent = user.name + ' (' + user.loginname + ')';
                    userSelect.appendChild(option);
                });
            }
        } catch (error) {
            console.error('加载用户列表失败:', error);
        }

        // 加载角色列表
        try {
            const response = await fetch(`${CONFIG.baseUrl}/api/roles?page=1&pageSize=100`);
            const result = await response.json();

            if (result.success) {
                const roleSelect = document.getElementById('roleSelect');
                roleSelect.innerHTML = '<option value="">请选择角色</option>';
                result.data.forEach(role => {
                    const option = document.createElement('option');
                    option.value = role.id;
                    option.textContent = role.name + (role.description ? ' - ' + role.description : '');
                    roleSelect.appendChild(option);
                });

                // 加载角色复选框
                const roleCheckboxes = document.getElementById('roleCheckboxes');
                roleCheckboxes.innerHTML = '';
                result.data.forEach(role => {
                    const div = document.createElement('div');
                    div.className = 'form-check';
                    div.innerHTML = '<input class="form-check-input" type="checkbox" value="' + role.id + '" id="role' + role.id + '">' +
                        '<label class="form-check-label" for="role' + role.id + '">' +
                        role.name + (role.description ? ' - ' + role.description : '') +
                        '</label>';
                    roleCheckboxes.appendChild(div);
                });
            }
        } catch (error) {
            console.error('加载角色列表失败:', error);
        }

        // 加载菜单列表
        try {
            const response = await fetch(`${CONFIG.baseUrl}/api/menus?page=1&pageSize=100`);
            const result = await response.json();

            if (result.success) {
                const menuCheckboxes = document.getElementById('menuCheckboxes');
                menuCheckboxes.innerHTML = '';
                result.data.forEach(menu => {
                    const div = document.createElement('div');
                    div.className = 'form-check';
                    div.innerHTML = '<input class="form-check-input" type="checkbox" value="' + menu.id + '" id="menu' + menu.id + '">' +
                        '<label class="form-check-label" for="menu' + menu.id + '">' +
                        '<i class="fas ' + getMenuIcon(menu.type) + ' me-2"></i>' + menu.name +
                        (menu.url ? '<small class="text-muted">(' + menu.url + ')</small>' : '') +
                        '</label>';
                    menuCheckboxes.appendChild(div);
                });
            }
        } catch (error) {
            console.error('加载菜单列表失败:', error);
            // 如果菜单API不存在，显示提示
            document.getElementById('menuCheckboxes').innerHTML =
                '<div class="alert alert-info">' +
                '<i class="fas fa-info-circle me-2"></i>' +
                '菜单管理功能需要额外的API支持' +
                '</div>';
        }
    }

    async function loadUserRoles() {
        const userId = document.getElementById('userSelect').value;
        if (!userId) return;

        try {
            const response = await fetch(`${CONFIG.baseUrl}/api/users/username/admin`); // 这里需要根据用户ID查询的API
            const result = await response.json();

            if (result.success && result.data) {
                // 重置所有角色复选框
                document.querySelectorAll('#roleCheckboxes input[type="checkbox"]').forEach(checkbox => {
                    checkbox.checked = false;
                });

                // 选中用户已有的角色
                if (result.data.roles) {
                    result.data.roles.forEach(role => {
                        const checkbox = document.getElementById(`role${role.id}`);
                        if (checkbox) {
                            checkbox.checked = true;
                        }
                    });
                }

                addOperationLog(`已加载用户 "${result.data.name}" 的角色信息`);
            }
        } catch (error) {
            console.error('加载用户角色失败:', error);
        }
    }

    async function loadRoleMenus() {
        const roleId = document.getElementById('roleSelect').value;
        if (!roleId) return;

        try {
            const response = await fetch(`${CONFIG.baseUrl}/api/roles/${roleId}`);
            const result = await response.json();

            if (result.success && result.data) {
                // 重置所有菜单复选框
                document.querySelectorAll('#menuCheckboxes input[type="checkbox"]').forEach(checkbox => {
                    checkbox.checked = false;
                });

                // 选中角色已有的菜单
                if (result.data.menus) {
                    result.data.menus.forEach(menu => {
                        const checkbox = document.getElementById(`menu${menu.id}`);
                        if (checkbox) {
                            checkbox.checked = true;
                        }
                    });
                }

                addOperationLog(`已加载角色 "${result.data.name}" 的菜单权限信息`);
            }
        } catch (error) {
            console.error('加载角色菜单失败:', error);
        }
    }

    async function updateUserRoles() {
        const userId = document.getElementById('userSelect').value;
        if (!userId) {
            alert('请先选择用户');
            return;
        }

        const selectedRoles = Array.from(document.querySelectorAll('#roleCheckboxes input[type="checkbox"]:checked'))
            .map(checkbox => checkbox.value);

        try {
            const response = await fetch(`${CONFIG.baseUrl}/api/users/${userId}/roles`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(selectedRoles)
            });

            const result = await response.json();

            if (result.success) {
                addOperationLog(`成功更新用户ID ${userId} 的角色设置`);
                alert('用户角色更新成功！');
            } else {
                addOperationLog(`更新用户角色失败: ${result.message}`);
                alert('更新失败: ' + result.message);
            }
        } catch (error) {
            console.error('更新用户角色失败:', error);
            addOperationLog('更新用户角色时发生错误');
            alert('更新过程中发生错误');
        }
    }

    async function updateRoleMenus() {
        const roleId = document.getElementById('roleSelect').value;
        if (!roleId) {
            alert('请先选择角色');
            return;
        }

        const selectedMenus = Array.from(document.querySelectorAll('#menuCheckboxes input[type="checkbox"]:checked'))
            .map(checkbox => checkbox.value);

        try {
            const response = await fetch(`${CONFIG.baseUrl}/api/roles/${roleId}/menus`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(selectedMenus)
            });

            const result = await response.json();

            if (result.success) {
                addOperationLog(`成功更新角色ID ${roleId} 的菜单权限设置`);
                alert('角色权限更新成功！');
            } else {
                addOperationLog(`更新角色权限失败: ${result.message}`);
                alert('更新失败: ' + result.message);
            }
        } catch (error) {
            console.error('更新角色权限失败:', error);
            addOperationLog('更新角色权限时发生错误');
            alert('更新过程中发生错误');
        }
    }

    function addOperationLog(message) {
        const logContainer = document.getElementById('operationLog');
        const timestamp = new Date().toLocaleString();
        const logEntry = document.createElement('p');
        logEntry.className = 'mb-2';
        logEntry.innerHTML = `<small>[${timestamp}]</small> ${message}`;

        logContainer.insertBefore(logEntry, logContainer.firstChild);

        // 限制日志数量
        if (logContainer.children.length > 10) {
            logContainer.removeChild(logContainer.lastChild);
        }
    }

    // 辅助函数
    function getGenderText(sex) {
        const genders = {1: '男', 2: '女'};
        return genders[sex] || '未知';
    }

    function getMenuIcon(type) {
        const icons = ['folder', 'file', 'cog', 'user', 'chart-bar'];
        return icons[type] || 'file';
    }

    function formatDate(dateString) {
        if (!dateString) return '未知';
        const date = new Date(dateString);
        return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN', {hour: '2-digit', minute:'2-digit'});
    }

    // 初始化
    document.addEventListener('DOMContentLoaded', function() {
        loadDashboardData();
        updateLastUpdateTime();
    });

    function loadDashboardData() {
        // 这里可以添加实际的统计API调用
        // 目前使用静态数据展示
        document.getElementById('userCount').textContent = '6';
        document.getElementById('roleCount').textContent = '3';
        document.getElementById('menuCount').textContent = '9';
        document.getElementById('relationCount').textContent = '9';
        document.getElementById('activeUsers').textContent = '6';
        document.getElementById('userWithRoles').textContent = '1';
        document.getElementById('avgRoles').textContent = '0.17';
    }

    function updateLastUpdateTime() {
        const now = new Date();
        document.getElementById('lastUpdate').textContent = now.toLocaleString('zh-CN');
    }
</script>
</body>
</html>
